<template>
  <view class="w-full h-screen bg-[#f8f9fb] flex flex-col">
    <view class="flex flex-col items-center my-8">
      <view class="relative">
        <image
          :src="
            model.avatar ||
            'https://youke1.picui.cn/s1/2025/09/23/68d213ce3793e.jpg'
          "
          class="w-[160rpx] h-[160rpx] rounded-full"
          mode="aspectFill"
        />
        <view
          class="absolute bottom-2 right-2 bg-white rounded-full p-2 shadow"
          @click="chooseAvatar"
        >
          <wd-icon name="camera" color="#4f7dfd"></wd-icon>
        </view>
      </view>
    </view>

    <wd-form ref="form" :model="model">
      <wd-cell-group border>
        <!-- Name -->
        <wd-input
          label="姓名"
          label-width="120rpx"
          prop="name"
          clearable
          v-model="model.name"
          placeholder="请输入姓名"
          :rules="[{ required: true, message: '请输入姓名' }]"
        />

        <wd-input
          label="电话"
          label-width="120rpx"
          prop="phone"
          clearable
          type="number"
          v-model="model.phone"
          placeholder="请输入电话"
          :rules="[
            { required: true, message: '请输入电话' },
            { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
          ]"
        />

        <wd-input
          label="邮箱"
          label-width="120rpx"
          prop="email"
          clearable
          v-model="model.email"
          placeholder="请输入邮箱"
          :rules="[
            { required: true, message: '请输入邮箱' },
            { type: 'email', message: '请输入正确的邮箱格式' }
          ]"
        />

        <wd-datetime-picker
          v-model="model.dob"
          label="生日"
          label-width="120rpx"
          prop="dob"
          type="date"
          placeholder="请选择生日"
          :rules="[{ required: true, message: '请选择生日' }]"
        />

        <wd-picker
          :columns="houseList"
          label="房屋"
          @confirm="handleConfirm"
          :rules="[{ required: true, message: '请选择房号' }]"
        />
      </wd-cell-group>
    </wd-form>

    <view
      class="fixed bottom-0 left-0 right-0 px-6 pb-6 bg-white safe-area-inset-bottom"
    >
      <wd-button block type="primary" @click="handleSubmit">保存</wd-button>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import useStore from '@/store'
import { uploadImage } from '@/utils/upload'
import { updateUser, getHouses } from '@/api/user'
import dayjs from 'dayjs'

const store = useStore()
const user = store.useUser.getUser

// 房屋列表
const houseList = ref<string[]>([])
const houseMapList = ref<IHouse[]>([])

// 表单数据模型
const model = reactive<{
  avatar: string
  name: string
  phone: string
  email: string
  dob: string
  house_id: number
}>({
  avatar: user.avatar || '',
  name: user.name || '',
  phone: user.phone || '',
  email: user.email || '',
  dob: user.birthday || '',
  house_id: user.house_id || 0
})

const form = ref()

// 确认选择房屋
const handleConfirm = (value: any) => {
  const house = houseMapList.value.find((item) => {
    return item.name === value.value
  })
  if (house) {
    model.house_id = house.id || 0
  }
  uni.setStorageSync('house_name', {
    id: house?.id || 0,
    name: value.value || ''
  })
}

// 选择头像
const chooseAvatar = async () => {
  const res = await uploadImage()
  model.avatar = res
}

// 提交表单
function handleSubmit() {
  form.value
    .validate()
    .then(async ({ valid }: { valid: boolean }) => {
      if (valid) {
        const res = await updateUser<any, IUser>({
          id: store.useUser.getUser.id || '',
          avatar: model.avatar,
          name: model.name,
          phone: model.phone,
          email: model.email,
          house_id: model.house_id,
          birthday: dayjs(model.dob).format('YYYY-MM-DD')
        })
        console.log(res, 'res')
        if (res.code === 200) {
          store.useUser.setUser(res.data)
          uni.showToast({
            title: '校验通过，保存成功！',
            icon: 'success'
          })
        }
      }
    })
    .catch((error: any) => {
      console.log(error, 'error')
      uni.showToast({
        title: '请完善表单信息',
        icon: 'none'
      })
    })
}

// 页面加载时获取房屋列表
onLoad(async () => {
  const res = await getHouses<IPaginationParams, IHouse>({
    page: 1,
    pageSize: 100
  })
  if (res.code === 200) {
    houseMapList.value = res.data.items
    houseList.value = res.data.items.map((item) => {
      return item.name as string
    })
  }
})
</script>
